<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {

    public function index(){
        $this->display('login');
    }

    public function login(){

        if(IS_POST){
            $user = I('post.');
            if(!isset($user['username']) || !isset($user['pwd']) ){
                $this->error('用户名密码必填',U('User/index'),2);
            }
            $find = M('yh_admin')->where(['username'=>$user['username']])->find();
            if(!$find){
                $this->error('用户名或密码错',U('User/index'),2);
            }

            if(!password_verify($user['pwd'],$find['password'])){
                $this->error('用户名或密码错',U('User/index'),2);

            }

            session('uid',$find['id']);
            session('user',$user['username']);

            $this->redirect('Index/index');
        }
        $this->display();
    }
    
    public function logout(){

        session_destroy();
        $this->redirect('User/index');
    }

    public function search(){
        $array = I('get.');

        if(empty($array['y_pwd']) || empty($array['x_pwd']) || empty($array['x_pwd1'])){
            echo json_encode(array('code'=>0,'msg'=>'请输入完整的信息'));exit;
        }

        $arr = M('yh_admin')->where(['id'=>$_SESSION['uid']])->find();
        $pwd = $arr['password'];//hash密码
        $res = password_verify($array['y_pwd'],$pwd);
        if(!$res){
            echo json_encode(array('code'=>1,'msg'=>'原密码输入有误'));exit;
        }

        $password = password_hash($array['x_pwd'],PASSWORD_DEFAULT);
        $str = array('password'=>$password);
        $res = M('yh_admin')->where(['id'=>$_SESSION['uid']])->save($str);
        if(!$res){
            echo json_encode(array('code'=>2,'msg'=>'修改失败'));exit;
        }
        echo json_encode(array('code'=>3,'msg'=>'修改成功'));exit;
    }

    public function upd(){
        $this->display();
    }
}